package monitoreo;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

/**
 *
 * @author Osvaldo Clua
 */
public class Monitoreable {

    ThreadMXBean MXB; // Management Bean
    ThreadInfo tInfo;
    long id;  // Java Thread id
    String soy = "";  // rol
    String yo; // Java Thread name
    long instPause; // instante de pausa
    private Estadistica est; // Estadisitcas a recolectar

    public Monitoreable(String soy, Estadistica est) {
        this.soy = soy;
        this.est = est;
    }

    protected long getTime() {
//        return System.currentTimeMillis();
        return (System.nanoTime());
    }

    public void endMonitor() {
        getEst().setInstStop(getTime());
        getEst().calcSS();
        tInfo = MXB.getThreadInfo(id);
        ThreadInfo consTI = MXB.getThreadInfo(id);
        getEst().setWaitedCount(consTI.getWaitedCount());
        getEst().setWaitedTIme(consTI.getWaitedTime());
    }

    public void startMonitor() {
        yo = Thread.currentThread().getName();
        id = Thread.currentThread().getId();
        est.setNombre(soy+" " + yo+" (tid=" + id + ")");
        MXB = ManagementFactory.getThreadMXBean();
        MXB.setThreadContentionMonitoringEnabled(true);
        getEst().setInstStart(getTime());
    }

    public void pauseMonitor() {
        instPause = getTime();
        getEst().setCantPause(getEst().getCantPause() + 1);
    }

    public void resumeMonitor() {
        long espera = getTime() - instPause;
        getEst().settPause(getEst().gettPause() + espera);
    }

    /**
     * @return the est
     */
    public Estadistica getEst() {
        return est;
    }
    public String getNombre(){
        return est.getNombre();
    }
}
